package com.yuanxiao.server;

import com.yuanxiao.coder.JSONSerializer;
import com.yuanxiao.coder.RpcDecoder;
import com.yuanxiao.coder.RpcEncoder;
import com.yuanxiao.coder.Serializer;
import com.yuanxiao.model.RpcRequest;
import com.yuanxiao.service.UserServerHandler;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;

public class RpcNetty {
    public static void startServer(String hostName,int port) throws InterruptedException {
        EventLoopGroup bossGroup = new NioEventLoopGroup();
        EventLoopGroup workerGroup = new NioEventLoopGroup();

        io.netty.bootstrap.ServerBootstrap bootstrap = new ServerBootstrap();
        bootstrap.group(bossGroup,workerGroup)
                .channel(NioServerSocketChannel.class)
                .childHandler(new ChannelInitializer<SocketChannel>() {

                    protected void initChannel(SocketChannel ch) throws Exception {
                        ChannelPipeline pipeline = ch.pipeline();
                        Serializer jsonSerializer =new JSONSerializer();
                        pipeline.addLast(new StringEncoder());
                        pipeline.addLast(new RpcDecoder(RpcRequest.class,jsonSerializer));
                        pipeline.addLast(new UserServerHandler());
                    }
                });
        bootstrap.bind(hostName, port).sync();
    }
}
